package com.itany.mall.dao.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import com.itany.mall.dao.ProductTypeDao;
import com.itany.mall.entity.ProductType;
import com.itany.mall.exception.DataAccessException;
import com.itany.mall.factory.Component;

import database.Database02;

@Component
public class ProductTypeDaoImpl implements ProductTypeDao {

	@Override
	public List<ProductType> selectAll() {
		List<ProductType> list = new ArrayList<ProductType>();
		File dir = new File(Database02.PRODUCT_TYPE_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.PRODUCT_TYPE_SUFFIX);
			}
		});
		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				ProductType t = (ProductType) ois.readObject();
				ois.close();
				list.add(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}
		return list;
	}

	@Override
	public ProductType selectByName(String name) {
		File dir = new File(Database02.PRODUCT_TYPE_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.PRODUCT_TYPE_SUFFIX);
			}
		});
		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				ProductType t = (ProductType) ois.readObject();
				ois.close();
				if (t.getName().equalsIgnoreCase(name)) {
					return t;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}
		return null;
	}

	@Override
	public void insert(ProductType t) {
		try {
			t.setId(Database02.autoIncrement(Database02.PRODUCT_TYPE_DIR));
			Database02.saveMallData(Database02.PRODUCT_TYPE_DIR, t, Database02.PRODUCT_TYPE_SUFFIX);
		} catch (IOException e) {
			e.printStackTrace();
			// dao 操作数据时, 发生异常
			// 需要抛运行时异常, 告诉service数据访问出错
			// 让程序停止, 让程序员解决问题
			throw new DataAccessException(e);
		}
	}

	@Override
	public ProductType selectById(long typeId) {
		File f = new File(Database02.PRODUCT_TYPE_DIR, typeId + Database02.PRODUCT_TYPE_SUFFIX);
		if (!f.exists()) {
			return null;
		}

		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));) {
			ProductType t = (ProductType) ois.readObject();
			return t;
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataAccessException(e);
		}

	}

}
